package com.brkj.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.brkj.util.view.BaseCoreActivity;
import com.dgl.sdk.util.FileDownloader;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import com.brkj.httpInterface.BaseAjaxParams;

import com.brkj.main.R;
import com.brkj.httpInterface.HttpInterface.HIF_checkUpdate;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CheckUpdate {

    private Map<String, String> update_soft = new HashMap<String, String>();
    private Context context;
    private ProgressDialog progressdialog;
    private String fromwho;

    private String url = null;
    private String fileName = null;

    public CheckUpdate(Context context, String formwho) {
        this.context = context;
        this.fromwho = formwho;
        progressdialog = new ProgressDialog(context);

    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            progressdialog.dismiss();
            if (msg.what == 1) {
                if (msg.obj.equals("update_soft")) {
                    show_update_PopupWindow();
                } else if (msg.obj.equals("is_latest")) {
                    if (fromwho.equals("from_aboutus")) {
                        show_is_latest_dialog();
                    }
                }

            }

        }
    };



    public void StartUpdate() {
        if (fromwho.equals("from_aboutus")) {
            progressdialog.setMessage("检查更新中...");
            progressdialog.show();
        }

        BaseAjaxParams params = new BaseAjaxParams();
        params.put(HIF_checkUpdate.params.VersionNum, ConstAnts.VERSION);
        params.put(HIF_checkUpdate.params.ApkName, ConstAnts.APK_NAME);

        FinalHttp fh = new FinalHttp();
        fh.post(HIF_checkUpdate.address, params, new AjaxCallBack<Object>() {

            @Override
            public void onSuccess(Object t) {
                // TODO Auto-generated method stub
                super.onSuccess(t);

                HIF_checkUpdate.result result =
                        JsonUtil.fromJson((String)t, HIF_checkUpdate.result.class);
                if(result!= null){
                    if(result.IsLatest == 1){
                        update_soft.put("content",
                                result.getUpdateContent());
                        update_soft.put("versionnum","");
                        update_soft.put("important","");
                        update_soft.put("url", result.getUrl());
                        update_soft.put("version","");

                        show_update_PopupWindow();
                    }else{
                        show_is_latest_dialog();
                    }
                }
            }

        });

//		new Thread() {
//			@Override
//			public void run() {
//				List<NameValuePair> list = new ArrayList<NameValuePair>();
//				list.add(new BasicNameValuePair("version.channelid",
//						ConstValue.CHANNEL_ID));
//				list.add(new BasicNameValuePair("version.versionnum",
//						ConstValue.VERSION));
//				list.add(new BasicNameValuePair("google",
//						""));
//
//				String result = SendService.receiveUpdateData(
//						"QueryVersion.action", list);
////
////				String result = SendService.receiveUpdateData(
////						"QueryVersion.action", list);
//				String content = null;
//				if (result != null) {
//					try {
//						content = URLDecoder.decode(result, "UTF-8");
//					} catch (UnsupportedEncodingException e) {
//						e.printStackTrace();
//					}
//
//					try {
//						JSONObject jsonObject = new JSONObject(content);
//						update_soft.put("content",
//								jsonObject.getString("content"));
//						update_soft.put("versionnum",
//								jsonObject.getString("versionnum"));
//						update_soft.put("important",
//								jsonObject.getString("important"));
//						update_soft.put("url", jsonObject.getString("url"));
//						update_soft.put("version",
//								jsonObject.getString("version"));
//					} catch (JSONException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//
//				}
//				Message msg = new Message();
//				msg.what = 1;
//				if ((update_soft.get("version") != null)
//						&& (update_soft.get("version").equals("yes"))) {
//					msg.obj = "update_soft";
//
//				} else {
//					msg.obj = "is_latest";
//				}
//				handler.sendMessage(msg);
//			};
//
//		}.start();

    }

    private void show_update_improt_PopupWindow() {
        final Dialog dialog = new Dialog(context, R.style.MyCustomDialog);
        dialog.setContentView(R.layout.update_soft);

        TextView update_text = (TextView) dialog.findViewById(R.id.update_text);
        Button btn_ok = (Button) dialog.findViewById(R.id.ok);
        Button btn_cancle = (Button) dialog.findViewById(R.id.cancle);

        update_text.setText(update_soft.get("content"));

        btn_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                show_update_PopupWindow();
            }
        });

        btn_cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }

        });
        dialog.show();
    }
    private void show_update_PopupWindow() {
        final Dialog dialog = new Dialog(context, R.style.MyCustomDialog);
        dialog.setContentView(R.layout.update_soft);

        TextView update_text = (TextView) dialog.findViewById(R.id.update_text);
        Button btn_ok = (Button) dialog.findViewById(R.id.ok);
        Button btn_cancle = (Button) dialog.findViewById(R.id.cancle);

        update_text.setText(update_soft.get("content"));

        btn_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                progressdialog.setMessage("正在下载新版本...");
                progressdialog.show();

                dialog.dismiss();
                url = update_soft.get("url");
                fileName = getFileName(url);

                File file = new File(ConstAnts.APK_DIR);
                if(!file.exists()){
                    file.mkdirs();
                }
                //dgltodo 更新下载
                FileDownloader fd = new FileDownloader(context, url, ConstAnts.APK_DIR, fileName,
                        2, new FileDownloader.DownloadCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onProgress(int progress) {
                        progressdialog.setMessage("正在下载新版本..." + progress + "%");
                    }

                    @Override
                    public void onComplete(String filePath) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);

                        intent.setDataAndType(Uri.fromFile(new File(ConstAnts.APK_DIR,
                                        fileName)),
                                "application/vnd.android.package-archive");

                        context.startActivity(intent);
                        progressdialog.dismiss();
                    }

                    @Override
                    public void onError(String error) {
                        Toast.makeText(context, "下载失败！",
                                Toast.LENGTH_SHORT).show();
                        progressdialog.dismiss();
                    }
                });

                fd.download();

            }
        });

        btn_cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                progressdialog.dismiss();
                dialog.dismiss();
            }

        });
        dialog.show();
    }

    private void show_is_latest_dialog() {
        if (fromwho.equals("from_aboutus")) {
            ((BaseCoreActivity)(context)).showToast("已经是最新版本");
            progressdialog.dismiss();
        }
    }

    private  String getFileName(String url) {
        String filename = "";
        boolean isok = false;
        // 从UrlConnection中获取文件名称
//        try {
//            URL myURL = new URL(url);
//
//            URLConnection conn = myURL.openConnection();
//            if (conn == null) {
//                return null;
//            }
//            Map<String, List<String>> hf = conn.getHeaderFields();
//            if (hf == null) {
//                return null;
//            }
//            Set<String> key = hf.keySet();
//            if (key == null) {
//                return null;
//            }
//            // Log.i("test", "getContentType:" + conn.getContentType() + ",Url:"
//            // + conn.getURL().toString());
//            for (String skey : key) {
//                List<String> values = hf.get(skey);
//                for (String value : values) {
//                    String result;
//                    try {
//                        result = new String(value.getBytes("ISO-8859-1"), "GBK");
//                        int location = result.indexOf("filename");
//                        if (location >= 0) {
//                            result = result.substring(location
//                                    + "filename".length());
//                            filename = result
//                                    .substring(result.indexOf("=") + 1);
//                            isok = true;
//                        }
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                    }// ISO-8859-1 UTF-8 gb2312
//                }
//                if (isok) {
//                    break;
//                }
//            }
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 从路径中获取
        if (filename == null || "".equals(filename)) {
            filename = url.substring(url.lastIndexOf("/") + 1);
        }
        return filename;
    }
}
